import User from '../schema/user'
import Role from '../schema/role'
import Store from '../schema/store'
import * as roleService from './roleService'
import Sequelize from 'sequelize'

const Op = Sequelize.Op

User.belongsTo(Role, {
    foreignKey: 'role_id',
    targetKey: 'id'
})
User.belongsTo(Store, {
    foreignKey: 'store_id',
    targetKey: 'id'
})

export async function getUserList() {
    return await User.findAll({
        include: [{
            model: Role,
            where: {
                role: {
                    [Op.ne]: 'ADMIN'
                }
            }
        }, {
            model: Store
        }],
        attributes: {
            exclude: ['password']
        }
    })
}

export async function getUserById(id) {
    return await User.findOne({
        include: [{
            model: Role,
            where: {
                role: {
                    [Op.ne]: 'ADMIN'
                }
            }
        }, {
            model: Store
        }],
        attributes: {
            exclude: ['password']
        },
        where: {
            id: {
                [Op.eq]: id
            }
        }
    })
}

export async function getUserByName(username) {
    return await User.findOne({
        include: [{
            model: Role
        }, {
            model: Store
        }],
        where: {
            username: {
                [Op.eq]: username
            }
        }
    })
}

export async function checkUsername(user) {
    if (user.id) {
        return await User.findOne({
            where: {
                username: {
                    [Op.eq]: user.username
                },
                id:{
                    [Op.ne]: user.id
                }
            }
        })
    }
    else {
        return await User.findOne({
            where: {
                username: {
                    [Op.eq]: user.username
                }
            }
        })
    }
}

export async function insertUser(user) {
    let role = await roleService.getUserIdByRole('USER')
    user.role_id = role.id
    user.password = user.username
    return await User.create(user)
}

export async function updateUser(user) {
    await User.update({
        username: user.username,
        name: user.name,
        store_id: user.store_id
    }, {
        fields: ['username', 'name', 'store_id'],
        where: {
            id: {
                [Op.eq]: user.id
            }
        }
    })
}

export async function deleteUser(id) {
    await User.destroy({
        where: {
            id: {
                [Op.eq]: id
            }
        }
    })
}

export async function resetPassword(id) {
    let user = await User.findByPk(id)
    user.password = user.username
    await user.save({
        fields: ['password']
    })
}
